package com.xomily.devops.agent.util;

import java.sql.Timestamp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.net.UnknownHostException;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * @version V1.0
 * @ClassName:CommonUtil.java
 * @author: xomily (2327742507@qq.com)
 * @date: 2021年11月18日
 * @Description: CommonUtil.java
 * @Copyright: 2021-2022 www.xomily.com. All rights reserved.
 */
public class CommonUtil {
	private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

	private final static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };
    //获取主机IP
    public static String getHostIp()
    {
        try
        {
            return InetAddress.getLocalHost().getHostAddress();
        }
        catch (UnknownHostException e)
        {
        }
        return "127.0.0.1";
    }

   //获取主机名
    public static String getHostName()
    {
        try
        {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
        }
        return "unknown";
    }
    

	// 字节转换
    public static double convertSize(long size) {
		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;
        double ret =0;
        ret = CommonUtil.formatDouble((double)  size / gb,2);
        return ret;        
	}
	
	// 获取中文格式的当前时间
	public static Timestamp getNow() {
		String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATETIME_PATTERN);
		Timestamp t = Timestamp.valueOf(dateFormat.format(new Date()));
		return t;
	}

	// 格式化小数点数字
    public static double formatDouble(double v, int scale)
    {
        if (scale < 0)
        {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = BigDecimal.ONE;
        return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
    }
    

	// 移除字符串中的%
	public static String removeChar(String str) {
		if (StringUtils.isEmpty(str)) {
			return "";
		}
		str = str.replace("%", "");
		return str;
	}

	// 获取相差N天的时间
	public static Date getDiffDate(Date datetimes, int days) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(datetimes);
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + days);
		return calendar.getTime();
	}

	// 单位统一转为g
	public static double toG(String s) {
		double result = 0;
		double mod = 1024;
		if (s.contains("M")) {
			double f = Double.valueOf(s.replace("M", ""));
			result = f / mod;
		} else if (s.contains("K")) {
			double f = Double.valueOf(s.replace("K", ""));
			result = (f / mod) / mod;
		} else if (s.contains("T")) {
			double f = Double.valueOf(s.replace("T", ""));
			result = f * 1024;
		} else if (s.contains("G")) {
			result = Double.valueOf(s.replace("G", ""));
		}
		return formatDouble(result, 2);
	}


	// 把byte[]数组转换成十六进制字符串表示形式
	private static String byteToHexString(byte[] b) {
		String s;
		char str[] = new char[16 * 2];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte bt = b[i];
			str[k++] = hexdigits[bt >>> 4 & 0xf];
			str[k++] = hexdigits[bt & 0xf];
		}
		s = new String(str);
		return s;
	}

	// 返回形式为数字跟字符串
	private static String byteToArray(byte b) {
		String[] digits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
		int ret = b;
		if (ret < 0) {
			ret += 256;
		}
		int d1 = ret / 16;
		int d2 = ret % 16;
		return digits[d1] + digits[d2];
	}

	// 转换字节数组为16进制字串
	private static String byteToString(byte[] bByte) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			buffer.append(byteToArray(bByte[i]));
		}
		return buffer.toString();
	}

	// 字符串转换成MD5码
	public static String stringToMD5(String s) {
		if (StringUtils.isEmpty(s)) {
			return "";
		}
		String result = null;
		try {
			result = new String(s);
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byteToString(md.digest(s.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	// 文件转换成MD5码
	public static String getMD5ForFile(String f) {
		FileInputStream stream = null;
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
			File file = new File(f);
			if (!file.exists()) {
				return "";
			}
			stream = new FileInputStream(file);
			byte[] buffer = new byte[4096];
			int length = -1;
			while ((length = stream.read(buffer)) != -1) {
				md.update(buffer, 0, length);
			}
			byte[] b = md.digest();
			return byteToHexString(b);
		} catch (Exception ex) {
			logger.error("文件转换MD5码异常！" + ex.toString());
			return null;
		} finally {
			try {
				if (null != stream) {
					stream.close();
				}
			} catch (IOException e) {
				logger.error("文件转换MD5码异常！" + e.toString());
			}
		}
	}

}
